package com.abocode.aichat.getway.aplication.endpoint;

import com.abocode.aichat.getway.endpoint.GatewayEndpointRegistry;
import com.abocode.aichat.server.endpoint.Endpoint;
import com.abocode.aichat.server.exception.EndpointRegisterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * Created by franky-14.
 */
@Service
public class RedisEndpointRegistryImpl implements GatewayEndpointRegistry {
    @Autowired
    private RedisTemplate redisTemplate;
    private String prefix = "server:";
    @Override
    public void unregister(Endpoint endpoint) throws EndpointRegisterException {
        String key = prefix + endpoint.getName() + ":" + endpoint.getDomain();
        redisTemplate.delete(key);
    }

    @Override
    public void register(Endpoint endpoint) throws EndpointRegisterException {
        String key = prefix + endpoint.getName() + ":" + endpoint.getDomain();
//        if (getRedisTemplate().hasKey(key)) {
//            throw new RuntimeException("double register");
//        }
        BoundHashOperations hashOperations = redisTemplate.boundHashOps(key);
        hashOperations.put("name", endpoint.getName());
        hashOperations.put("domain", endpoint.getDomain());
    }
}
